// const ErrorCode = require('../utils/ErrorCode')
const ResultVo = require('../utils/ResultVo')
// const Exception = require('../exception/Exception')
const LabelService = require('../service/LabelService')
const fs = require('fs')
const path = require('path')


class LabelController {
  async create(req, res, next) {
    const { categoryId, label } = req.body

    if (req.file.size === 0) {
      res.status(400).json(ResultVo.fail(-1, '文件不可为空'))
      return
    }
    const file = req.file
    const ext = path.extname(file.originalname)
    const icon = `/upload/${file.filename}${ext}`
    await LabelService.create({ categoryId, label, icon }).catch(err => next(err))
    fs.renameSync(file.path, `public${icon}`)
    res.json(ResultVo.successNull())
  }

  async findLabels(req, res, next) {
    const result = await LabelService.getLabels().catch(err => next(err))
    res.json(ResultVo.success(result))
  }

  async updateLabel(req, res, next) {
    const { id } = req.params
    const data = req.body
    Object.keys(data).forEach(item => {
      if (data[item] === '') {
        delete data[item]
      }
    })
    const result = await LabelService.updateLabel(id, data).catch(err => next(err))
    res.json(ResultVo.success(result))
  }

  async changeIcon(req, res, next) {
    const { id } = req.params
    if (req.file.size === 0) {
      res.status(400).json(ResultVo.fail(-1, '文件不可为空'))
      return
    }
    const file = req.file
    const ext = path.extname(file.originalname)
    const icon = `/upload/${file.filename}${ext}`
    const info = await LabelService.getLabelById(id).catch(err => next(err))
    fs.unlinkSync(path.join('public', info.icon))
    const result = await LabelService.updateLabel(id, { icon })
    res.json(ResultVo.success(result))
  }

  async removeLabel(req, res, next) {
    const { id } = req.params
    const info = await LabelService.getLabelById(id).catch(err => next(err))
    fs.unlinkSync(path.join('public', info.icon))
    await LabelService.removeLabel(id).catch(err => next(err))
    res.json(ResultVo.successNull())
  }
}

module.exports = new LabelController()